class GoodsList {
    constructor() {
        this.userActions = document.querySelector('.user-actions');
        this.goodsList = document.querySelector('#goodsList');
        this.currentPage = 1;
        this.pageSize = 12;
        this.totalPages = 1;
        
        this.init();
    }

    init() {
        // 先检查登录状态
        if (!this.checkLoginStatus()) {
            return;  // 如果未登录，不继续初始化
        }
        this.loadGoodsList();
        this.bindEvents();
    }

    // 检查登录状态
    checkLoginStatus() {
        const token = localStorage.getItem('token');
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');

        if (token && userInfo) {
            // 已登录状态
            this.userActions.innerHTML = `
                <span>您好，${userInfo.nickname || userInfo.username}！</span>
                <a href="profile.html" class="login-btn">个人中心</a>
                <a href="javascript:void(0)" class="login-btn" onclick="window.goodsList.handleLogout()">退出登录</a>
            `;
            return true;
        } else {
            // 未登录，返回首页
            alert('请先登录！');
            window.location.href = 'index.html';
            return false;
        }
    }

    // 绑定事件
    bindEvents() {
        // 分页按钮事件
        document.querySelectorAll('#firstPage, #firstPageBottom').forEach(btn => {
            btn.addEventListener('click', () => this.goToPage(1));
        });
        
        document.querySelectorAll('#prevPage, #prevPageBottom').forEach(btn => {
            btn.addEventListener('click', () => this.goToPage(this.currentPage - 1));
        });
        
        document.querySelectorAll('#nextPage, #nextPageBottom').forEach(btn => {
            btn.addEventListener('click', () => this.goToPage(this.currentPage + 1));
        });
        
        document.querySelectorAll('#lastPage, #lastPageBottom').forEach(btn => {
            btn.addEventListener('click', () => this.goToPage(this.totalPages));
        });

        // 跳转页码
        document.querySelector('#jumpPage').addEventListener('click', () => {
            const page = parseInt(document.querySelector('#pageInput').value);
            if (page && page > 0 && page <= this.totalPages) {
                this.goToPage(page);
            } else {
                alert('请输入有效的页码');
            }
        });

        // 每页显示数量
        document.querySelector('#pageSizeSelect').addEventListener('change', (e) => {
            this.pageSize = parseInt(e.target.value);
            this.goToPage(1);
        });
    }

    // 加载商品列表
    async loadGoodsList() {
        // 再次检查登录状态，以防在加载过程中登录状态改变
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = 'index.html';
            return;
        }

        try {
            const response = await fetch(`http://localhost:8888/goods/list?current=${this.currentPage}&pagesize=${this.pageSize}`);
            const data = await response.json();
            
            if (data.code === 1) {
                this.renderGoodsList(data.list);
                this.totalPages = Math.ceil(data.total / this.pageSize);
                this.updatePaginationInfo();
            } else {
                alert(data.message || '获取商品列表失败');
            }
        } catch (error) {
            alert('获取商品列表失败，请检查网络连接');
            console.error('获取商品列表错误：', error);
        }
    }

    // 渲染商品列表
    renderGoodsList(list) {
        this.goodsList.innerHTML = list.map(item => `
            <div class="goods-item" onclick="window.goodsList.goToDetail(${item.goods_id})">
                <img src="${item.img_big_logo}" alt="${item.title}" class="goods-item-image">
                <div class="goods-item-title">${item.title}</div>
                <div class="goods-item-price">¥${item.current_price}</div>
                <div class="goods-item-original">¥${item.price}</div>
                ${item.is_hot ? '<span class="goods-tag">热销</span>' : ''}
                ${item.is_sale ? `<span class="goods-tag">${item.sale_type}</span>` : ''}
            </div>
        `).join('');
    }

    // 更新分页信息
    updatePaginationInfo() {
        document.querySelector('.pagination-info span').textContent = `${this.currentPage} / ${this.totalPages}`;
        
        // 更新按钮状态
        const prevBtns = document.querySelectorAll('#prevPage, #prevPageBottom');
        const nextBtns = document.querySelectorAll('#nextPage, #nextPageBottom');
        
        prevBtns.forEach(btn => btn.disabled = this.currentPage === 1);
        nextBtns.forEach(btn => btn.disabled = this.currentPage === this.totalPages);
    }

    // 跳转到指定页
    goToPage(page) {
        if (page < 1 || page > this.totalPages) return;
        this.currentPage = page;
        this.loadGoodsList();
    }

    // 跳转到商品详情
    goToDetail(id) {
        window.location.href = `goods-detail.html?id=${id}`;
    }

    // 处理退出登录
    async handleLogout() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        
        try {
            const response = await fetch(`http://localhost:8888/users/logout/${userInfo.id}`, {
                headers: {
                    'authorization': localStorage.getItem('token')
                }
            });

            const data = await response.json();
            
            if (data.code === 1) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                alert('退出登录成功！');
                window.location.reload();
            } else {
                alert(data.message || '退出登录失败，请重试');
            }
        } catch (error) {
            alert('退出登录失败，请检查网络连接');
            console.error('退出登录错误：', error);
        }
    }
}

// 初始化商品列表页
window.goodsList = new GoodsList(); 